import 'dart:ui';

import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_fixed_height_confirm_button_widget/common_fixed_height_confirm_button_widget.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/utils/router_utils.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_dialog_utils.dart';
import 'package:flutter/material.dart';
import 'dart:ui' as ui;

import 'package:flutter/services.dart';

class CameraDistanceWidget extends StatefulWidget {
  final double distance;
  final Function(int distance) onSelect;

  CameraDistanceWidget({this.distance = 0, this.onSelect});

  static Future<double> navigatorPush(BuildContext context, double distance,
      {Function(int distance) onSelect}) {
    return VgDialogUtils.showCommonBottomDialog<double>(
        context: context,
        child: CameraDistanceWidget(distance: distance, onSelect: onSelect));
  }

  @override
  State<StatefulWidget> createState() {
    return CameraDistanceWidgetState();
  }
}

class CameraDistanceWidgetState extends State<CameraDistanceWidget> {
  double value;

  /// 加载图片
//  Future _loadImage(String path) async {
//    var data = await rootBundle.load(path);
//    var codec = await ui.instantiateImageCodec(data.buffer.asUint8List());
//    var info = await codec.getNextFrame();
//    return info.image;
//  }

  @override
  void initState() {
//    _loadImage('images/').then((value) {
//      setState(() {
//        _image=value;
//      });
//    });
    value = widget.distance;
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      //设置距离顶部位置
      height: 184,
      decoration: BoxDecoration(
          shape: BoxShape.rectangle,
          color: Color(0xff21263c),
          borderRadius: BorderRadius.only(
              topRight: Radius.circular(10), topLeft: Radius.circular(10))),
      child: Column(
        children: <Widget>[
          Container(
            height: 54,
            child: Stack(
              children: <Widget>[
                Positioned(
                  left: 16,
                  top: 15,
                  bottom: 15,
                  child: Text(
                    "摄像头启动距离",
                    style: TextStyle(
                        fontSize: 17,
                        fontWeight: FontWeight.bold,
                        color: Colors.white),
                  ),
                ),
                Positioned(
                  right: 15,
                  top: 15,
                  bottom: 15,
                  child: CommonFixedHeightConfirmButtonWidget(
                    text: "保存",
                    isAlive: true,
                    width: 70,
                    height: 30,
                    unSelectTextStyle: TextStyle(
                        color: VgColors.INPUT_BG_COLOR,
                        fontSize: 14,
                        fontWeight: FontWeight.w600),
                    selectedTextStyle: TextStyle(
                        color: Colors.white,
                        fontSize: 14,
                        fontWeight: FontWeight.w600),
                    unSelectBgColor: ThemeRepository.getInstance()
                        .getTextEditHintColor_3A3F50(),
                    selectedBgColor:
                    ThemeRepository.getInstance().getPrimaryColor_1890FF(),
                    onTap: () {
                      RouterUtils.pop(context, result: value);
                    },
                  ),
                )
              ],
            ),
          ),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: 28),
            child: SliderTheme(
              data: SliderThemeData(
                  overlayShape: RoundSliderOverlayShape(overlayRadius: 16),
                  thumbShape: ThumbShape(),
                  trackHeight: 16,
                  trackShape: CustomTrackShape(4),
                  inactiveTickMarkColor: Colors.transparent,
                  activeTickMarkColor: Colors.transparent,
                  inactiveTrackColor: Colors.white,
                  activeTrackColor: Colors.white,
                  valueIndicatorColor: Colors.white),
              child: Slider(
                min: 0,
                max: 4,
                value: value,
                divisions: 4,
                onChanged: (value) {
                  setState(() {
                    this.value = value;
                  });
                },
              ),
            ),
          ),
          Center(
            child: Row(
              children: <Widget>[
                _valueText("最近", 0.0),
                _valueText("近", 1.0),
                _valueText("适中", 2.0),
                _valueText("远", 3.0),
                _valueText("最远", 4.0)
              ],
            ),
          )
        ],
      ),
    );
  }


  _valueText(String text, double position) {
    return Expanded(
      child: GestureDetector(
        onTap: () {
          setState(() {
            value = position;
          });
        },
        child: Center(child: Text(
            text,
            style: TextStyle(
                color: position == value ? Color(0xff1890ff) : Color(
                    0xffD0E0F7),
                fontSize: 13)),
        ),
      ),
    );
  }
}

///刻度部分
class CustomTrackShape extends RectangularSliderTrackShape {
  int divisions;

  CustomTrackShape(this.divisions);

  @override
  void paint(PaintingContext context, Offset offset,
      {@required RenderBox parentBox,
        @required SliderThemeData sliderTheme,
        @required Animation<double> enableAnimation,
        @required TextDirection textDirection,
        @required Offset thumbCenter,
        bool isDiscrete = false,
        bool isEnabled = false}) {
    assert(context != null);
    assert(offset != null);
    assert(parentBox != null);
    assert(sliderTheme != null);
    assert(sliderTheme.disabledActiveTrackColor != null);
    assert(sliderTheme.disabledInactiveTrackColor != null);
    assert(sliderTheme.activeTrackColor != null);
    assert(sliderTheme.inactiveTrackColor != null);
    assert(sliderTheme.thumbShape != null);
    assert(enableAnimation != null);
    assert(textDirection != null);
    assert(thumbCenter != null);
    assert(isEnabled != null);
    assert(isDiscrete != null);
    // If the slider track height is less than or equal to 0, then it makes no
    // difference whether the track is painted or not, therefore the painting
    // can be a no-op.
    if (sliderTheme.trackHeight <= 0) {
      return;
    }

    Paint horizontalLinePaint = Paint()
      ..color = Colors.white
      ..style = PaintingStyle.fill;

    final Rect trackRect = getPreferredRect(
      parentBox: parentBox,
      offset: offset,
      sliderTheme: sliderTheme,
      isEnabled: isEnabled,
      isDiscrete: isDiscrete,
    );
    double subWidth = (trackRect.width) / divisions;
    for (int i = 0; i < 5; i++) {
      context.canvas.drawLine(
          Offset(trackRect.left + subWidth * i, thumbCenter.dy),
          Offset(trackRect.left + subWidth * i, thumbCenter.dy + 8),
          horizontalLinePaint);
    }
    //两横线
    final Rect leftTrackSegment = Rect.fromLTRB(
        trackRect.left, trackRect.top, thumbCenter.dx, trackRect.bottom);
    if (!leftTrackSegment.isEmpty) {
      context.canvas.drawLine(Offset(leftTrackSegment.left, thumbCenter.dy),
          Offset(leftTrackSegment.right, thumbCenter.dy), horizontalLinePaint);

      context.canvas.drawLine(
          Offset(trackRect.left, thumbCenter.dy),
          Offset(leftTrackSegment.left, thumbCenter.dy + 8),
          horizontalLinePaint);
    }

    final Rect rightTrackSegment = Rect.fromLTRB(
        thumbCenter.dx, trackRect.top, trackRect.right, trackRect.bottom);
    if (!rightTrackSegment.isEmpty)
      context.canvas.drawLine(Offset(rightTrackSegment.left, thumbCenter.dy),
          Offset(rightTrackSegment.right, thumbCenter.dy), horizontalLinePaint);

    context.canvas.drawLine(
        Offset(rightTrackSegment.right, thumbCenter.dy),
        Offset(rightTrackSegment.right, thumbCenter.dy + 8),
        horizontalLinePaint);
  }
}

///游标形状
class ThumbShape extends SliderComponentShape {


  @override
  Size getPreferredSize(bool isEnabled, bool isDiscrete) {
    return Size(12, 16);
  }

  @override
  void paint(PaintingContext context,
      Offset center,
      {Animation<double> activationAnimation,
        Animation<double> enableAnimation,
        bool isDiscrete,
        TextPainter labelPainter,
        RenderBox parentBox,
        SliderThemeData sliderTheme,
        TextDirection textDirection,
        double value,
        double textScaleFactor,
        Size sizeWithOverflow}) {
    Canvas canvas = context.canvas;
    Path path = Path()..moveTo(center.dx - 6, center.dy - 8);
    path.lineTo(center.dx + 6, center.dy - 8);
    path.lineTo(center.dx, center.dy + 8);
    canvas.drawPath(
        path,
        Paint()
          ..style = PaintingStyle.fill
          ..color = Color(0xff1890ff));
  }


  // @override
  // void paint(PaintingContext context, Offset center,
  //     {Animation<double> activationAnimation,
  //       Animation<double> enableAnimation,
  //       bool isDiscrete,
  //       TextPainter labelPainter,
  //       RenderBox parentBox,
  //       SliderThemeData sliderTheme,
  //       TextDirection textDirection,
  //       double value,}) {
  //   Canvas canvas = context.canvas;
  //   Path path = Path()..moveTo(center.dx - 6, center.dy - 8);
  //   path.lineTo(center.dx + 6, center.dy - 8);
  //   path.lineTo(center.dx, center.dy + 8);
  //   canvas.drawPath(
  //       path,
  //       Paint()
  //         ..style = PaintingStyle.fill
  //         ..color = Color(0xff1890ff));
  //
  // }
}

class CustomSliderComponentShape extends RangeSliderTickMarkShape {
  @override
  Size getPreferredSize({SliderThemeData sliderTheme, bool isEnabled}) {
    return Size(1, 10);
  }

  @override
  void paint(PaintingContext context, Offset center,
      {RenderBox parentBox,
        SliderThemeData sliderTheme,
        Animation<double> enableAnimation,
        Offset startThumbCenter,
        Offset endThumbCenter,
        bool isEnabled,
        TextDirection textDirection}) {
    context.canvas.drawPath(
        Path()
          ..moveTo(center.dx, center.dy)
          ..lineTo(center.dx, center.dy + 10),
        Paint()
          ..color = Colors.white
          ..style = PaintingStyle.fill);
  }
}
